// pages/health/index.js
Page({
  data: {
    today: '',
    currentMood: '',
    moodLevel: 5,
    moodDescription: '',
    moodRecords: [],
    weeklyMoodStats: {
      averageMood: 0,
      totalRecords: 0,
      positiveDays: 0
    },
    moodOptions: [
      { level: 1, emoji: '😭', text: '非常糟糕', color: '#FF5722' },
      { level: 2, emoji: '😞', text: '糟糕', color: '#FF9800' },
      { level: 3, emoji: '😐', text: '一般', color: '#FFC107' },
      { level: 4, emoji: '🙂', text: '不错', color: '#4CAF50' },
      { level: 5, emoji: '😊', text: '很好', color: '#2196F3' }
    ]
  },

  onLoad: function () {
    this.updateDate();
    this.loadTodayRecords();
    this.loadWeeklyStats();
  },

  onShow: function () {
    this.loadTodayRecords();
    this.loadWeeklyStats();
  },

  // 格式化日期为中文
  formatDate: function (date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    const weekday = weekdays[date.getDay()];
    
    return `${year}年${month}月${day}日 星期${weekday}`;
  },

  // 更新日期
  updateDate: function () {
    const now = new Date();
    const today = this.formatDate(now);
    
    this.setData({
      today: today
    });
  },

  // 选择心情等级
  selectMood: function (e) {
    const level = parseInt(e.currentTarget.dataset.level);
    const mood = this.data.moodOptions.find(item => item.level === level);
    
    this.setData({
      moodLevel: level,
      currentMood: mood.text
    });
  },

  // 输入心情描述
  inputDescription: function (e) {
    this.setData({
      moodDescription: e.detail.value
    });
  },

  // 记录心情
  recordMood: function () {
    if (!this.data.moodDescription.trim()) {
      wx.showToast({
        title: '请描述一下今天的心情',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    const mood = this.data.moodOptions.find(item => item.level === this.data.moodLevel);
    
    const record = {
      date: this.data.today,
      level: this.data.moodLevel,
      emoji: mood.emoji,
      text: mood.text,
      description: this.data.moodDescription,
      timestamp: Date.now()
    };

    this.saveMoodRecord(record);
    
    // 清空输入
    this.setData({
      moodDescription: ''
    });

    wx.showToast({
      title: '心情记录成功！',
      icon: 'success',
      duration: 2000
    });
  },

  // 保存心情记录到云端
  saveMoodRecord: function (record) {
    const app = getApp();
    if (!app.globalData.isLogin) {
      // 未登录时保存到本地
      let records = wx.getStorageSync('moodRecords') || [];
      
      // 检查今天是否已有记录，如果有则替换
      const todayIndex = records.findIndex(item => item.date === this.data.today);
      if (todayIndex !== -1) {
        records[todayIndex] = record;
      } else {
        records.push(record);
      }
      
      wx.setStorageSync('moodRecords', records);
      return;
    }

    // 已登录时保存到云端
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'moodRecord',
        action: 'add',
        data: record
      }
    }).then(res => {
      if (res.result.success) {
        console.log('心情记录已保存到云端');
        // 同时保存到本地作为缓存
        let records = wx.getStorageSync('moodRecords') || [];
        const todayIndex = records.findIndex(item => item.date === this.data.today);
        if (todayIndex !== -1) {
          records[todayIndex] = record;
        } else {
          records.push(record);
        }
        wx.setStorageSync('moodRecords', records);
      } else {
        console.error('云端保存失败:', res.result.message);
        // 云端保存失败时保存到本地
        let records = wx.getStorageSync('moodRecords') || [];
        const todayIndex = records.findIndex(item => item.date === this.data.today);
        if (todayIndex !== -1) {
          records[todayIndex] = record;
        } else {
          records.push(record);
        }
        wx.setStorageSync('moodRecords', records);
      }
    }).catch(err => {
      console.error('云端调用失败:', err);
      // 云端调用失败时保存到本地
      let records = wx.getStorageSync('moodRecords') || [];
      const todayIndex = records.findIndex(item => item.date === this.data.today);
      if (todayIndex !== -1) {
        records[todayIndex] = record;
      } else {
        records.push(record);
      }
      wx.setStorageSync('moodRecords', records);
    });
  },

  // 加载今日记录
  loadTodayRecords: function () {
    const app = getApp();
    if (!app.globalData.isLogin) {
      // 未登录时从本地加载
      const records = wx.getStorageSync('moodRecords') || [];
      const today = this.formatDate(new Date());
      const todayRecord = records.find(record => record.date === today);
      
      if (todayRecord) {
        this.setData({
          moodLevel: todayRecord.level,
          currentMood: todayRecord.text,
          moodDescription: todayRecord.description
        });
      }
      return;
    }

    // 已登录时从云端加载
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'moodRecord',
        action: 'getToday'
      }
    }).then(res => {
      if (res.result.success) {
        const todayRecords = res.result.data || [];
        if (todayRecords.length > 0) {
          const todayRecord = todayRecords[0]; // 每天只有一条记录
          this.setData({
            moodLevel: todayRecord.level,
            currentMood: todayRecord.text,
            moodDescription: todayRecord.description
          });
        }
        
        // 同步到本地缓存
        wx.setStorageSync('moodRecords', todayRecords);
      }
    }).catch(err => {
      console.error('云端加载失败:', err);
      // 云端加载失败时从本地加载
      const records = wx.getStorageSync('moodRecords') || [];
      const today = this.formatDate(new Date());
      const todayRecord = records.find(record => record.date === today);
      
      if (todayRecord) {
        this.setData({
          moodLevel: todayRecord.level,
          currentMood: todayRecord.text,
          moodDescription: todayRecord.description
        });
      }
    });
  },

  // 加载周统计
  loadWeeklyStats: function () {
    const app = getApp();
    if (!app.globalData.isLogin) {
      // 未登录时从本地计算
      const records = wx.getStorageSync('moodRecords') || [];
      const now = new Date();
      const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      
      const weeklyRecords = records.filter(record => {
        const recordDate = new Date(record.date);
        return recordDate >= weekStart;
      });
      
      if (weeklyRecords.length > 0) {
        const totalMood = weeklyRecords.reduce((sum, record) => sum + record.level, 0);
        const averageMood = (totalMood / weeklyRecords.length).toFixed(1);
        const positiveDays = weeklyRecords.filter(record => record.level >= 4).length;
        
        this.setData({
          weeklyMoodStats: {
            averageMood: parseFloat(averageMood),
            totalRecords: weeklyRecords.length,
            positiveDays: positiveDays
          }
        });
      }
      return;
    }

    // 已登录时从云端加载
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'moodRecord',
        action: 'getWeekly'
      }
    }).then(res => {
      if (res.result.success) {
        const weeklyRecords = res.result.data || [];
        
        if (weeklyRecords.length > 0) {
          const totalMood = weeklyRecords.reduce((sum, record) => sum + record.level, 0);
          const averageMood = (totalMood / weeklyRecords.length).toFixed(1);
          const positiveDays = weeklyRecords.filter(record => record.level >= 4).length;
          
          this.setData({
            weeklyMoodStats: {
              averageMood: parseFloat(averageMood),
              totalRecords: weeklyRecords.length,
              positiveDays: positiveDays
            }
          });
        }
      }
    }).catch(err => {
      console.error('云端统计加载失败:', err);
      // 云端加载失败时从本地计算
      const records = wx.getStorageSync('moodRecords') || [];
      const now = new Date();
      const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      
      const weeklyRecords = records.filter(record => {
        const recordDate = new Date(record.date);
        return recordDate >= weekStart;
      });
      
      if (weeklyRecords.length > 0) {
        const totalMood = weeklyRecords.reduce((sum, record) => sum + record.level, 0);
        const averageMood = (totalMood / weeklyRecords.length).toFixed(1);
        const positiveDays = weeklyRecords.filter(record => record.level >= 4).length;
        
        this.setData({
          weeklyMoodStats: {
            averageMood: parseFloat(averageMood),
            totalRecords: weeklyRecords.length,
            positiveDays: positiveDays
          }
        });
      }
    });
  },

  // 查看心情历史
  viewMoodHistory: function () {
    wx.navigateTo({
      url: '/pages/health/history'
    });
  },

  // 获取心情建议
  getMoodAdvice: function () {
    const level = this.data.moodLevel;
    let advice = '';
    
    if (level <= 2) {
      advice = '今天心情不太好，建议：\n• 听听喜欢的音乐\n• 出去散散步\n• 和朋友聊聊天\n• 做些让自己开心的事';
    } else if (level === 3) {
      advice = '今天心情一般，建议：\n• 尝试新的事物\n• 给自己一些小奖励\n• 保持积极心态';
    } else {
      advice = '今天心情不错！建议：\n• 保持这种好心情\n• 分享快乐给他人\n• 记录下美好的时刻';
    }
    
    wx.showModal({
      title: '心情建议',
      content: advice,
      showCancel: false,
      confirmText: '知道了'
    });
  }
});
